#pragma Once
#include "RingQueue.hpp"
#include "Task.hpp"
#include <ctime>
#include <unistd.h>


void *Consumer(void *args)
{
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args);

    while (true)
    {
        // 接受任务/数据
        Task t;
        rq->pop(&t);
        // 处理任务/数据
        t.run();
        std::cout << "已处理任务=> " << t.GetTask() << t.GetResult() << std::endl;
    }
}

// std::string opers = "+-*/%";
void *Producer(void *args)
{
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args);

    while (true)
    {
        // 设置任务
        char op = opers[rand() % opers.size()];
        int data1 = rand() % 10 + 1;
        int data2 = rand() % 10;
        Task t(data1, data2, op);

        // 发送任务/数据
        rq->push(t);
        std::cout << "发送一个任务=> " << t.GetTask() << "??" << std::endl;
        sleep(1);
    }
}

int main()
{
    srand(time(nullptr));
    
    RingQueue<Task> *rq = new RingQueue<Task>(5); //环形队列
    
    //创造多个线程
    pthread_t c[5], p[3];

    for (int i = 0; i < 5; i++)
    {
        pthread_create(c + i, nullptr, Consumer, rq);
    }

    for (int i = 0; i < 3; i++)
    {
        pthread_create(p + i, nullptr, Producer, rq);
    }

    for (int i = 0; i < 5; i++)
    {
        pthread_join(c[i], nullptr);
    }

    for (int i = 0; i < 3; i++)
    {
        pthread_join(p[i], nullptr);
    }

    delete rq;
    return 0;
}
